package com.google.code.qsecurity.server.util;

import java.util.Date;

import javax.servlet.http.HttpSession;

import com.google.code.qsecurity.server.domain.User;

public class SessionUtil {
	private static final String USER_ATTRIBUTE = "user";
	
	// inactive interval in seconds
	private static final int MAX_INACTIVE_INTERVAL_S = 2*60*60; // 2 hours
	
	// inactive interval in milliseconds
	private static final long MAX_INACTIVE_INTERVAL_MS =
			MAX_INACTIVE_INTERVAL_S * 1000;  
	
	public static void storeUser(HttpSession session, String email) {
		session.setAttribute(USER_ATTRIBUTE, email);
	}
	
	public static void storeUser(HttpSession session, User user) {
		storeUser(session, user.getEmail());
	}
	
	public static void removeUser(HttpSession session, String email) {
		session.removeAttribute(USER_ATTRIBUTE);
	}
	
	public static void removeUser(HttpSession session, User user) {
		removeUser(session, user.getEmail());
	}
	
	public static boolean isUserStored(HttpSession session, String email) {
		String sessionAttribute = (String) session.getAttribute(USER_ATTRIBUTE);
		
		if (sessionAttribute == null)
			return false;
		
		return email.equalsIgnoreCase(sessionAttribute);
	}
	
	public static void isUserStored(HttpSession session, User user) {
		isUserStored(session, user.getEmail());
	}
	
	public static Date initSession(HttpSession session, String email) {
		session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL_S);
		storeUser(session, email);
		long now = System.currentTimeMillis();
		return new Date(now + MAX_INACTIVE_INTERVAL_MS);
	}
	
	public static void initSession(HttpSession session, User user) {
		session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL_S);
		storeUser(session, user.getEmail());
	}
}
